import Blockutils from "@/utils/BlockUtils";
import Mota, { MotaInterface } from "@/mota";
import { ImageName } from "@/mota/data/ImageLoader";

export default class MessgeUtils implements MotaInterface {

	public readonly Mota: Mota;

	public show: boolean = false;

	public unit: ImageName = "勇士";

	public background: ImageName = "石地板";

	public message: string = "";

	public length: number = this.message.length;

	public speed: number = 10;

	public pos: number = 0;

	public progress: number = 0;

	public isOver: boolean = true;

	public block: Blockutils = new Blockutils();

	public ZIndex: number = 4;

	public constructor(mota: Mota) {
		this.Mota = mota;
	}

	public Show(unit: ImageName, background: ImageName, message: string): Promise<void> {
		return this.block.Wait(async () => {
			this.unit = unit;
			this.background = background;
			this.message = message;
			this.length = this.message.length;
			this.pos = 0;
			this.progress = 0;
			this.isOver = false;
			this.show = true;
		}, () => {
			this.show = false;
		});
	}

	public InView(): boolean {
		const { show } = this;
		return show;
	}

	public JudgeKey: MotaInterface["JudgeKey"] = (keyUtils): void => {
		if (!this.InView()) { return; }

		const { isOver, Mota: { speedUtils } } = this;

		for (const key of keyUtils.keyHistory) {
			if (key === " ") {
				if (isOver) {
					this.block.Release();
				} else {
					const speed = speedUtils.speed.Value;
					this.pos = this.length * speed;
				}
				keyUtils.delete(key);
			}
		}
	}

	public Draw: MotaInterface["Draw"] = (draw) => {
		if (!this.InView()) { return; }

		const { _2d } = draw;
		const { Mota: { speedUtils } } = this;
		const { unit, background, message, isOver, progress } = this;

		const top: 1 | 6 = 6;
		_2d.save();

		draw.translate(4, 0);
		draw.translate(1, top);

		draw.DrawBackground([background, [0, 0, 8, 3]]);
		_2d.strokeStyle = "#FFFFFF";
		draw.SetLineWidth(1 / 8);

		draw.strokeRect(0, 0, 9, 4);
		draw.DrawImage(unit, true, speedUtils.progress.Value, [0.5, 0.5, 1, 1]);
		draw.SetLineWidth(1 / 16);
		draw.strokeRect(0.5, 0.5, 1, 1);

		_2d.fillStyle = "#FFFFFF";
		draw.SetFont(800, 1 / 1.75, "Mota");
		_2d.textAlign = "center";
		draw.fillText(unit, 5, 0.8);

		const fontsize = 1 / 2;
		draw.SetFont(500, fontsize, "Mota");
		_2d.textAlign = "left";
		const drawMessage = message.substring(0, progress);
		draw.DrawTextAutoLine(drawMessage, 2.4, 1.55, fontsize, 1.5, 5.5);

		if (isOver) {
			draw.SetFont("bold", 1 / 3, "Mota");
			_2d.textAlign = "right";
			draw.fillText("-按任意键继续- ", 8.85, 3.65);
		}

		_2d.restore();
	}

	public Trigger(): void {
		if (!this.isOver) {
			const { Mota: { speedUtils: { speed: { Value: speed } } } } = this;
			this.progress = Math.floor(this.pos / speed)
			if (this.progress < this.length) {
				this.pos += speed;
			} else {
				this.pos = this.length;
				this.isOver = true;
			}
		}
	}
}
